package com.xiaoxing.yunshu.mvp.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.dds.soap.SoapListener;
import com.dds.soap.SoapParams;
import com.dds.soap.SoapUtil;
import com.hss01248.frescopicker.FrescoIniter;
import com.hss01248.photoouter.PhotoCallback;
import com.hss01248.photoouter.PhotoUtil;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.LogUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xiaoxing.yunshu.R;
import com.xiaoxing.yunshu.di.component.DaggerYunShuRuKuMainComponent;
import com.xiaoxing.yunshu.di.module.YunShuRuKuMainModule;
import com.xiaoxing.yunshu.mvp.contract.YunShuRuKuMainContract;
import com.xiaoxing.yunshu.mvp.presenter.YunShuRuKuMainPresenter;
import com.xiaoxing.yunshu.mvp.ui.adapter.YunShuRuKuMainAdapter;
import com.xiaoxing.yunshu.mvp.ui.entity.LoginReceiver;
import com.xiaoxing.yunshu.mvp.ui.entity.MaterialDriverMappingCangKu;
import com.xiaoxing.yunshu.mvp.ui.entity.MaterialDriverMappingChanPin;
import com.xiaoxing.yunshu.mvp.ui.entity.YunShuMain;

import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import me.iwf.photopicker.utils.ProxyTools;
import me.jessyan.armscomponent.commonres.utils.BottomDialogUtil;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import me.jessyan.armscomponent.commonsdk.utils.Utils;
import pub.devrel.easypermissions.EasyPermissions;

import static android.support.v7.widget.DividerItemDecoration.VERTICAL;
import static com.jess.arms.base.BaseConstants.NAME_SPACE;
import static com.jess.arms.base.BaseConstants.SCAN_REQUEST_CODE;
import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.APP_YUN_SHU_RU_KU_MAIN_ACTIVITY)
public class YunShuRuKuMainActivity extends BaseActivity<YunShuRuKuMainPresenter> implements YunShuRuKuMainContract.View, OnRefreshListener, YunShuRuKuMainAdapter.CheckInterface, YunShuRuKuMainAdapter.WanChengInterface, EasyPermissions.PermissionCallbacks {


    private static boolean mIsNeedDemo = true;
    @BindView(R.id.empty_text)
    TextView empty_text;
    @BindView(R.id.empty_image)
    ImageView empty_image;

    @BindView(R.id.empty)
    View mEmptyLayout;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.refreshLayout)
    RefreshLayout mRefreshLayout;

    @BindView(R.id.nice_spinner)
    Spinner nice_spinner;
    @BindView(R.id.btnRight)
    ImageView mBtnRight;
    private YunShuRuKuMainAdapter mAdapter;
    private List<YunShuMain.DataBean> mDataBeanList = new ArrayList<>();
    private List<MaterialDriverMappingCangKu> groups = new ArrayList<MaterialDriverMappingCangKu>();// 组元素数据列表
    private Map<String, List<MaterialDriverMappingChanPin>> children = new HashMap<String, List<MaterialDriverMappingChanPin>>();// 子元素数据列表
    private Map<Integer, Integer> mGroupsPosition = new HashMap<>();
    private BottomDialogUtil mBottomDialogUtilShare;
    private List<LoginReceiver> loginReceivers;

    private String selectDriverId;
    private String mOutId;
    private String mid;
    private String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};

    @OnClick(R.id.btnRight)
    void scan() {
        if (getPermission()) {

            Intent newIntent = new Intent(this, ScanActivity.class);
            mSharedPreferencesHelper.putInt(SCAN_REQUEST_CODE, 101);
            // 开始一个新的 Activity等候返回结果
            startActivityForResult(newIntent, 101);
        }

    }

    private boolean getPermission() {
        if (EasyPermissions.hasPermissions(this, permissions)) {
            return true;
        } else {
            EasyPermissions.requestPermissions(this, "需要获取您的相册、照相使用权限", 1, permissions);
            return false;
        }

    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerYunShuRuKuMainComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .yunShuRuKuMainModule(new YunShuRuKuMainModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_yun_shu_main; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        ToolbarUtils.initToolbarTitleNoBack(this, "货物到达列表");
        mBtnRight.setImageResource(R.drawable.icon_scan);

        PhotoUtil.init(this, new FrescoIniter());//第二个参数根据具体依赖库而定

        initRefreshLayout();
        initRecyclerView();
        initEmpty();

        loginReceivers = mSharedPreferencesHelper.getListData("loginReceivers", LoginReceiver.class);

        if (loginReceivers != null && loginReceivers.size() > 0) {

            ArrayList<String> list = new ArrayList<String>();
            for (int i = 0; i < loginReceivers.size(); i++) {
                list.add(loginReceivers.get(i).getDisplay_name());
            }

            ArrayAdapter adapter1 = new ArrayAdapter(this, R.layout.simple_spinner_item_driver, android.R.id.text1, list);
            nice_spinner.setAdapter(adapter1);
            nice_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    selectDriverId = String.valueOf(loginReceivers.get(position).getId());
//                    ArmsUtils.makeText(YunShuRuKuMainActivity.this, "selectDriverId=" + selectDriverId);
                    getDriverTaskMaterialArrive();

                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });

        }

    }

    private void initRefreshLayout() {
        mRefreshLayout.setRefreshHeader(new
                ClassicsHeader(this).setSpinnerStyle(SpinnerStyle.FixedBehind).setPrimaryColorId(R.color.public_colorPrimary).setAccentColorId(android.R.color.white));
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setEnableRefresh(false);
        mRefreshLayout.setEnableLoadMore(false);
    }

    private void initRecyclerView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(YunShuRuKuMainActivity.this));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(YunShuRuKuMainActivity.this, VERTICAL));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(mAdapter = new YunShuRuKuMainAdapter(YunShuRuKuMainActivity.this, groups, children, mGroupsPosition));


        mAdapter.setCheckInterface(this);// 关键步骤1,设置复选框接口
        mAdapter.setWanChengInterface(this);// 设置完成

    }

    private void initEmpty() {
        empty_image.setImageResource(R.drawable.ic_empty);
        empty_text.setTextColor(Color.parseColor("#CFCFCF"));
        empty_text.setText("暂无数据");
    }

    /**
     * 入库列表
     */
    private void getDriverTaskMaterialArrive() {

        showLoading();

        String methodName = "GetDriverReceivePeopleTaskMaterialArrive";

        SoapUtil soapUtil = SoapUtil.getInstance(this);
        soapUtil.setDotNet(true);
        SoapParams params = new SoapParams();
        params.put("driverId", selectDriverId);
        params.put("phone", mSharedPreferencesHelper.getString(BaseConstants.MOBILE_PHONE));
        /**
         * 请求
         */
        soapUtil.callEntry(getUrl(), NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                groups.clear();
                children.clear();
                mGroupsPosition.clear();

                List<MaterialDriverMappingCangKu> materialDriverMappingCangKuList = new ArrayList<>();

                if (object.getPropertyCount() == 0) {
                    mEmptyLayout.setVisibility(View.VISIBLE);
                } else {

                    mEmptyLayout.setVisibility(View.GONE);

                    SoapObject driverTaskMaterialArriveResult = (SoapObject) object.getProperty("GetDriverReceivePeopleTaskMaterialArriveResult");
                    mOutId = driverTaskMaterialArriveResult.getPropertyAsString("out_id");
                    LogUtils.debugEInfo("mOutId=" + mOutId);
                    for (int i = 0; i < driverTaskMaterialArriveResult.getPropertyCount(); i++) {
                        SoapObject materialdrivermappingAndroidJsonInstore = (SoapObject) driverTaskMaterialArriveResult.getProperty(i);

                        MaterialDriverMappingCangKu materialDriverMappingCangKu = new MaterialDriverMappingCangKu();

                        materialDriverMappingCangKu.setFromstorename(materialdrivermappingAndroidJsonInstore.getPropertyAsString("tostoreaddress"));
                        materialDriverMappingCangKu.setFromstoreaddress(materialdrivermappingAndroidJsonInstore.getPropertyAsString("tostoreaddress"));
//                    materialDriverMappingCangKu.setTasks(materialdrivermappingCangKuBean.getPropertyAsString("fromstoreaddress"));
                        List<MaterialDriverMappingChanPin> materialDriverMappingChanPinList = new ArrayList<>();

                        SoapObject materialdrivermapping = (SoapObject) materialdrivermappingAndroidJsonInstore.getProperty("tasks");

                        for (int i1 = 0; i1 < materialdrivermapping.getPropertyCount(); i1++) {
                            SoapObject materialdrivermappingBean = (SoapObject) materialdrivermapping.getProperty(i1);

                            MaterialDriverMappingChanPin materialDriverMappingChanPin = new MaterialDriverMappingChanPin();
                            materialDriverMappingChanPin.setMaterial(materialdrivermappingBean.getPropertyAsString("material"));
                            materialDriverMappingChanPin.setReceivephone(materialdrivermappingBean.getPropertyAsString("receivephone"));
                            materialDriverMappingChanPin.setReceiveusername(materialdrivermappingBean.getPropertyAsString("receiveusername"));
                            materialDriverMappingChanPin.setTargetproject(materialdrivermappingBean.getPropertyAsString("targetproject"));
                            materialDriverMappingChanPin.setFromspaceaddress(materialdrivermappingBean.getPropertyAsString("fromstoreaddress"));
                            materialDriverMappingChanPin.setFromstorename(materialdrivermappingBean.getPropertyAsString("fromstorename"));
                            materialDriverMappingChanPin.setFromspacename(materialdrivermappingBean.getPropertyAsString("fromspacename"));
                            materialDriverMappingChanPin.setFromspaceaddress(materialdrivermappingBean.getPropertyAsString("fromspaceaddress"));
                            materialDriverMappingChanPin.setTostoreaddress(materialdrivermappingBean.getPropertyAsString("tostoreaddress"));
                            materialDriverMappingChanPin.setDrivername(materialdrivermappingBean.getPropertyAsString("drivername"));
                            materialDriverMappingChanPin.setId(materialdrivermappingBean.getPropertyAsString("id"));
                            materialDriverMappingChanPin.setMid(materialdrivermappingBean.getPropertyAsString("mid"));
                            materialDriverMappingChanPin.setDriverid(materialdrivermappingBean.getPropertyAsString("driverid"));
                            materialDriverMappingChanPin.setIsactive(materialdrivermappingBean.getPropertyAsString("isactive"));
                            materialDriverMappingChanPin.setIsbeginscan(materialdrivermappingBean.getPropertyAsString("isbeginscan"));
                            materialDriverMappingChanPin.setIsendscan(materialdrivermappingBean.getPropertyAsString("isendscan"));
                            materialDriverMappingChanPin.setIsontransport(materialdrivermappingBean.getPropertyAsString("isontransport"));
                            materialDriverMappingChanPin.setNum(materialdrivermappingBean.getPropertyAsString("num"));
                            materialDriverMappingChanPin.setAssigntime(materialdrivermappingBean.getProperty("assigntime") == null ? "" : materialdrivermappingBean.getProperty("assigntime").toString());
                            materialDriverMappingChanPin.setBegintime(materialdrivermappingBean.getProperty("begintime") == null ? "" : materialdrivermappingBean.getProperty("begintime").toString());
                            materialDriverMappingChanPin.setEndtime(materialdrivermappingBean.getProperty("endtime") == null ? "" : materialdrivermappingBean.getProperty("endtime").toString());

                            materialDriverMappingChanPinList.add(materialDriverMappingChanPin);
                        }

                        materialDriverMappingCangKu.setTasks(materialDriverMappingChanPinList);
                        materialDriverMappingCangKuList.add(materialDriverMappingCangKu);
                    }


                    mAdapter.setDataItems(getSampleItems(materialDriverMappingCangKuList));
                    mAdapter.notifyDataSetChanged();
                    mAdapter.expandAll();
                }
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());


    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    public List<YunShuRuKuMainAdapter.OrderListItem> getSampleItems(List<MaterialDriverMappingCangKu> materialDriverMappingCangKuList) {
        List<YunShuRuKuMainAdapter.OrderListItem> items = new ArrayList<>();


        for (int i = 0; i < materialDriverMappingCangKuList.size(); i++) {

            int groupPosition = items.size();
            mGroupsPosition.put(groupPosition, i);

            MaterialDriverMappingCangKu materialDriverMappingCangKu = materialDriverMappingCangKuList.get(i);

            groups.add(new MaterialDriverMappingCangKu(groupPosition + "", materialDriverMappingCangKu.getFromstorename(), materialDriverMappingCangKu.getFromstoreaddress()));
            items.add(new YunShuRuKuMainAdapter.OrderListItem(materialDriverMappingCangKu));

            List<MaterialDriverMappingChanPin> materialDriverMappingChanPinList = materialDriverMappingCangKu.getTasks();

            List<MaterialDriverMappingChanPin> products = new ArrayList<MaterialDriverMappingChanPin>();


            for (int i1 = 0; i1 < materialDriverMappingChanPinList.size(); i1++) {

                MaterialDriverMappingChanPin materialDriverMappingChanPin = materialDriverMappingChanPinList.get(i1);

                products.add(materialDriverMappingChanPin);

                items.add(new YunShuRuKuMainAdapter.OrderListItem(groupPosition, materialDriverMappingChanPin, i1));
            }

            children.put(String.valueOf(groupPosition), products);// 将组元素的一个唯一值，这里取Id，作为子元素List的Key

        }
        items.add(new YunShuRuKuMainAdapter.OrderListItem("", "", "", ""));


        return items;
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mRefreshLayout.finishRefresh();

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 101) {
            Bundle bundle = data.getExtras();
            mid = bundle.getString("scan_result");
            setIsScan(mid);
            if (getPermission()) {
                shangChuangTuPian(mid);
            }
        } else {
            //onActivityResult里一行代码回调
            if (resultCode != 0)
                PhotoUtil.onActivityResult(this, requestCode, resultCode, data);
        }

    }

    /**
     * 设置是否扫描
     *
     * @param mid
     */
    private void setIsScan(String mid) {
        for (int k = 0; k < groups.size(); k++) {
            MaterialDriverMappingCangKu group = groups.get(k);
            List<MaterialDriverMappingChanPin> childs = children.get(group.getId());
            for (int i = 0; i < childs.size(); i++) {
                // 不全选中
                if (childs.get(i).getMid().equals(mid)) {
                    childs.get(i).setIsendscan("1");
                }
            }
        }
        mAdapter.notifyDataSetChanged();
    }

    private void shangChuangTuPian(String mid) {
        LinearLayout root = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.sales_client_bottom_dialog_pai_zhao, null);
        Button btn_xiang_ce = root.findViewById(me.iwf.photopicker.R.id.btn_xiang_ce);
        Button ben_xiang_ji = root.findViewById(me.iwf.photopicker.R.id.ben_xiang_ji);
        Button btn_qu_xiao = root.findViewById(me.iwf.photopicker.R.id.btn_qu_xiao);
        btn_qu_xiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();
            }
        });
        btn_xiang_ce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (mBottomDialogUtilShare != null)
//                    mBottomDialogUtilShare.dismissDiaolog();

                PhotoUtil.begin()
                        .setNeedCropWhenOne(true)
                        .setNeedCompress(true)
                        .setMaxSelectCount(1)
                        .setCropMuskOval()
                        .setSelectGif()
                        /*.setFromCamera(false)
                        .setMaxSelectCount(5)
                        .setNeedCropWhenOne(false)
                        .setNeedCompress(true)
                        .setCropRatio(16,9)*/
                        .start(YunShuRuKuMainActivity.this, 33, ProxyTools.getShowMethodInfoProxy(new PhotoCallback() {
                            @Override
                            public void onFail(String msg, Throwable r, int requestCode) {
                            }

                            @Override
                            public void onSuccessSingle(String originalPath, String compressedPath, int requestCode) {
                                try {
                                    transportScanArrive(mid, ArmsUtils.fileToBase64(compressedPath));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }

                            @Override
                            public void onSuccessMulti(List<String> originalPaths, List<String> compressedPaths, int requestCode) {
//                                refresh1(originalPaths);
                            }

                            @Override
                            public void onCancel(int requestCode) {
                            }
                        }));
            }
        });
        ben_xiang_ji.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (mBottomDialogUtilShare != null)
//                    mBottomDialogUtilShare.dismissDiaolog();

                PhotoUtil.cropAvatar(true)
                        .start(YunShuRuKuMainActivity.this, 23, ProxyTools.getShowMethodInfoProxy(new PhotoCallback() {
                            @Override
                            public void onFail(String msg, Throwable r, int requestCode) {
                            }

                            @Override
                            public void onSuccessSingle(String originalPath, String compressedPath, int requestCode) {
                                try {
                                    transportScanArrive(mid, ArmsUtils.fileToBase64(compressedPath));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onSuccessMulti(List<String> originalPaths, List<String> compressedPaths, int requestCode) {
                            }

                            @Override
                            public void onCancel(int requestCode) {
                            }
                        }));
            }
        });

        mBottomDialogUtilShare = new BottomDialogUtil(YunShuRuKuMainActivity.this, root);

        mBottomDialogUtilShare.showDiaolog();


    }

    /**
     * 8.物料到达目的地,每扫描一个物料,都需要调用一次
     *
     * @param mid 物料的id
     */
    private void transportScanArrive(String mid, String imgData) {

        showLoading();

        String methodName = "TransportScanArrive";

        SoapUtil soapUtil = SoapUtil.getInstance(this);
        soapUtil.setDotNet(true);
        SoapParams params = new SoapParams();
        params.put("driverId", mSharedPreferencesHelper.getString(BaseConstants.UID));
        params.put("mid", mid);
        params.put("imgStr", imgData);
        //TODO 照片为空的时候在提示弹出拍照选择照片
        //TODO 如果没扫描，出库列表就提交，数据怎么核对

        /**
         * 请求
         */
        soapUtil.callEntry(getUrl(), NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();
                ArmsUtils.snackbarText("提交成功");

                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());


    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
        if (requestCode == 103) {
            if (!TextUtils.isEmpty(mid))
                shangChuangTuPian(mid);
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        ArmsUtils.makeText(this, "相关权限获取成功");
    }


    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        ArmsUtils.makeText(this, "请同意相关权限，否则功能无法使用");
    }

    @Override
    public void checkGroup(int groupPosition, boolean isChecked) {


        MaterialDriverMappingCangKu group = groups.get(groupPosition);
        List<MaterialDriverMappingChanPin> childs = children.get(group.getId());
        for (int i = 0; i < childs.size(); i++) {
            childs.get(i).setChoosed(isChecked);
        }
        if (isAllCheck()) {
//            allChekbox.setChecked(true);
        } else {
//            allChekbox.setChecked(false);
        }

        mAdapter.notifyDataSetChanged();
    }

    private boolean isAllCheck() {

        for (MaterialDriverMappingCangKu group : groups) {
            if (!group.isChoosed())
                return false;
        }
        return true;
    }

    @Override
    public void checkChild(int groupPosition, int childPosition, boolean isChecked) {

        boolean allChildSameState = true;// 判断改组下面的所有子元素是否是同一种状态
        MaterialDriverMappingCangKu group = groups.get(mGroupsPosition.get(groupPosition));

        List<MaterialDriverMappingChanPin> childs = children.get(group.getId());
        for (int i = 0; i < childs.size(); i++) {
            // 不全选中
            if (childs.get(i).isChoosed() != isChecked) {
                allChildSameState = false;
                break;
            }
        }
        //获取店铺选中商品的总金额
        if (allChildSameState) {
            group.setChoosed(isChecked);// 如果所有子元素状态相同，那么对应的组元素被设为这种统一状态
        } else {
            group.setChoosed(false);// 否则，组元素一律设置为未选中状态
        }

//        group.setChoosed(true);

        if (isAllCheck() && allChildSameState) {
//            allChekbox.setChecked(true);// 全选
        } else {
//            allChekbox.setChecked(false);// 反选
        }
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void wangCheng() {

        if (!isAllScan()) {
            ArmsUtils.snackbarText("还有物料未扫描！");
            return;
        }

        if (!isAllCheck()) {
            ArmsUtils.snackbarText("还有选项未确认！");
            return;
        }
        transportInstoreFinish();

    }

    private boolean isAllScan() {
        for (int k = 0; k < groups.size(); k++) {
            MaterialDriverMappingCangKu group = groups.get(k);
            List<MaterialDriverMappingChanPin> childs = children.get(group.getId());
            for (int i = 0; i < childs.size(); i++) {
                // 不全选中
                if (childs.get(i).getIsendscan().equals("0")) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 7.整车到达目的地,调用此方法
     */
    private void transportInstoreFinish() {

        showLoading();

//        String methodName = "TransportInstoreFinish";
        String methodName = "TransportOutStoreFinish";

        SoapUtil soapUtil = SoapUtil.getInstance(this);
        soapUtil.setDotNet(true);
        SoapParams params = new SoapParams();
        params.put("driverId", mSharedPreferencesHelper.getString(BaseConstants.UID));
        params.put("out_id", mOutId);

        /**
         * 请求
         */
        soapUtil.callEntry(getUrl(), NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();
                ArmsUtils.snackbarText("货物到达完成");
//                setRuKuTrue();
//                setChuKuFalse();
//                setYunShuJieShuFalse();
                Utils.navigation(YunShuRuKuMainActivity.this, RouterHub.APP_YUN_SHU_WAN_CHENG_MAIN_ACTIVITY);
                killMyself();
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());


    }

    private void setYunShuJieShuFalse() {
        mSharedPreferencesHelper.putBoolean(BaseConstants.YUN_SHU_JIE_SHU, false);
    }

    private void setRuKuTrue() {
        mSharedPreferencesHelper.putBoolean(BaseConstants.IS_RU_KU, true);
    }

    private void setChuKuFalse() {
        mSharedPreferencesHelper.putBoolean(BaseConstants.IS_CHU_KU, false);
    }


    /**
     * 是否入库，true 已出库 false 未出库
     * 出库之后执行到达目的地之后的方法，反之执行出库相关的方法
     *
     * @return
     */
    private boolean isRuKu() {
        return mSharedPreferencesHelper.getBoolean(BaseConstants.IS_RU_KU);
    }

    private boolean isChuKu() {
        return mSharedPreferencesHelper.getBoolean(BaseConstants.IS_CHU_KU);
    }


}
